import { createRouter, createWebHistory } from "vue-router";
import { getToken } from '@/utils/cookie'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: "/c-oj/login",
            name: "login",
            component: () => import("@/views/Login.vue")
        },{
            path: "/c-oj/home", 
            name: "home",
            component: () => import("@/views/Home.vue"),
            redirect: "/c-oj/home/question",
            children: [
                {
                    path: "question",
                    name: "question",
                    component: () => import("@/views/Question.vue"),
                    meta: {showBanner: true}
                },
                {
                    path: "exam",
                    name: "exam",
                    component: () => import("@/views/Exam.vue"),
                    meta: {showBanner: true}
                },
                {
                    path: "user/exam",
                    name: "userExam",
                    component: () => import("@/views/UserExam.vue"),
                    meta: {showBanner: false}
                },
                {
                    path: "user/detail",
                    name: "userDetail",
                    component: () => import("@/views/UserDetail.vue"),
                    meta: {showBanner: false}
                },
            ]
        },
    ]
})

//路由前置检测
router.beforeEach((to, from,next) => {
  //判断是否存在cookie信息
  if(getToken()) {  //已经登录过了
    if(to.path === '/c-oj/login') {  //已经登录过了，无需登录直接跳转主页面
      next({ path: '/c-oj/home/question' })
    }else {
      next() //该干嘛干嘛去
    }
  }else{ //还未登录
    if(to.path !== '/c-oj/home/question' 
        && to.path !== '/c-oj/home/exam' 
        && to.path !== '/c-oj/login') {   //访问的不是题目列表页或者竞赛列表页面或者登录界面，强行跳转主页面
      next({ path:'/c-oj/home/question' })
    }else {
      next()
    }
  }
})

export default router;